package com.guxingke.typecho4j.widget.provider.content;

import java.util.HashMap;
import java.util.Map;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.Content;
import com.guxingke.typecho4j.util.ControllerUtil;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;

/**
 * 具体文章的内容组件<br>
 * 
 * @author guxingke
 * */
public class PostWidget extends ContentBaseWidget implements WidgetProvider {
	private Map<Long, Content> postCache = new HashMap<Long, Content>();

	@Override
	public void excute(Controller controller) throws Typecho4jException {
		Long cid = null;
		try {
			cid = Long.parseLong(ControllerUtil
					.getUrlPara(controller));
		} catch (NumberFormatException e) {
			throw new Typecho4jException(404);
		}

		Content post = getPost(cid);
		if (post == null) {
			throw new Typecho4jException(404);
		}
		controller.setAttr("post", post);
		controller.setAttr("commentsNum", post.get("commentsNum"));
	}

	private Content getPost(Long cid) {
		if (postCache.containsKey(cid)) {
			return postCache.get(cid);
		}
		Content result = getPostById(cid);
		if (result != null) {
			postCache.put(cid, result);
		}
		return result;
	}

	@Override
	public void refresh() {
		// 重置缓存
		this.postCache.clear();
	}
}
